import os
import re
import subprocess



class Converter:

    def __init__(self, pictDirPath=None):
        self.SetPictDirPath(pictDirPath)

    def SetPictDirPath(self, pictDirPath):
        self.pictDirPath = pictDirPath

    def GetPictures(self):
        filenames = [i for i in os.listdir(self.pictDirPath) if not i.startswith('.')]
        cmd = ['sips', '-g', 'pixelWidth', '-g', 'pixelHeight', '-g', 'dpiWidth', '[filename.jpg]']
 #       pictures = []
        numberPattern = re.compile(".*?(\d+)")
        for i, filename in enumerate(filenames):
            cmd[7] = os.path.join(self.pictDirPath, filename)
            pipe = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            pstdout, pstderr = pipe.communicate()
            if pstdout is not None and len(pstderr) == 0:
                pstdout = pstdout.split("\n")
                width = numberPattern.search(pstdout[1]).group(1)
                height = numberPattern.search(pstdout[2]).group(1)
                dpi = numberPattern.search(pstdout[3]).group(1)
                orientation = 'H' if int(width) >= int(height) else 'V'
 #               yield (i, filename, orientation, width, height, dpi)
                yield {'i':i, 'filename':filename, 'orientation':orientation, 'width':width, 
                       'height':height, 'dpi':dpi}
 #               pictures.append({'filename':filename, 'orientation':orientation, 'width':width, 
 #                                'height':height, 'dpi':dpi})
 #       return pictures

    def Convert(self, selectedFilenames, outputDirPath):
        cmd = ['sips', '-s', 'format', 'jpeg', '[filename.tif]', '--out', '[filename.jpg]']
        print '* Format conversion (from "'+self.pictDirPath+'" to "'+outputDirPath+'")'
        for i, tifFilename in enumerate(selectedFilenames):
            jpgFilename = '.'.join(tifFilename.split('.')[:-1]) + '.jpg'
            print "\t"+'- '+tifFilename+' -> '+jpgFilename
            yield (i+1, tifFilename, jpgFilename)
            cmd[4] = os.path.join(self.pictDirPath, tifFilename)
            cmd[6] = os.path.join(outputDirPath, jpgFilename)
            pipe = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE)
            pipe.communicate()

    def Process(self, selectedImages, outputDirPath, flipHorizontal=False, flipVertical=False,
                rotate=False, rotateDegrees=0, resample=False, resampleBy='Width', resampleValue=0,
                resampleValue2=0):
        cmd = ['sips']
        print '* Picture transformation (from "'+self.pictDirPath+'" to "'+outputDirPath+'")'
        if flipHorizontal:
            cmd += ['-f', 'horizontal']
        if flipVertical:
            cmd += ['-f', 'vertical']
        if rotate:
            cmd += ['-r', str(rotateDegrees)]
        if resample:
            if resampleBy == 'Width':
                cmd += ['--resampleWidth', str(resampleValue)]
            elif resampleBy == 'Height':
                cmd += ['--resampleHeight', str(resampleValue)]
            elif resampleBy == 'DPI':
                cmd += ['-s', 'dpiWidth', str(resampleValue), '-s', 'dpiHeight', str(resampleValue),
                        '--resampleWidth', '[newWidth]']
                cmdResampleDPIIndex = len(cmd) - 1
            elif resampleBy == 'Max size':
                cmd += ['[resampleOrientation]', '[newWidth]'] 
        cmd += ['[filename]', '--out', '[filename]']
        for i, selectedImage in enumerate(selectedImages):
            print "\t"+'- '+' '.join(cmd[:-3])+' '+selectedImage['filename']
            yield (i+1, selectedImage['filename'])
            cmd[-3] = os.path.join(self.pictDirPath, selectedImage['filename'])
            cmd[-1] = os.path.join(outputDirPath, selectedImage['filename'])
            if resample and resampleBy == 'DPI':
                newWidth = (int(selectedImage['width']) * resampleValue) / int(selectedImage['dpi'])
                cmd[-4] = str(newWidth)
            if resample and resampleBy == 'Max size':
                if (int(selectedImage['height'])*resampleValue / int(selectedImage['width']) <= resampleValue2):
                    cmd[-5] = '--resampleWidth'
                    cmd[-4] = str(resampleValue)
                else:
                    cmd[-5] = '--resampleHeight'
                    cmd[-4] = str(resampleValue2)
            pipe = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE)
            pipe.communicate()

    def ReorderRename(self, filenames, outputDirPath):
        print '* Reordering and renaming (from "'+self.pictDirPath+'" to "'+outputDirPath+'")'
        for currentFilename, newFilename in filenames:
            print "\t"+'- '+currentFilename+' -> '+newFilename
            os.rename(os.path.join(self.pictDirPath, currentFilename), 
                      os.path.join(outputDirPath, newFilename)+'.tmp')
        for currentFilename, newFilename in filenames:
            os.rename(os.path.join(outputDirPath, newFilename)+'.tmp', 
                      os.path.join(outputDirPath, newFilename))



